<?php
namespace App\Http\Controllers;

/**
 * 
 * 首页控制器
 * 
 * @author maqu
 *
 */

use App\Models\Good;
use App\Services\BaiduMapService;
use App\Services\CacheService;
use App\Services\LayoutRecommendService;
use App\Services\PintuanService;
use App\Services\StoreService;
use App\Services\TourOrderService;
use App\Services\TourService;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;

use App\Services\AdService;

class HomeController extends BaseController {

    /**
     * 获取轮播图
     * @return mixed
     */
    public function getCarousels(){

        $adposition = intval(Input::get('ad_position'));
        if(!$adposition) {
            return $this->args_invalid();
        }

        //轮播图
        $ad_service = new AdService();
        $carousels =$ad_service->getCarousels($adposition);
        unset($ad_service);

        return $this->success($carousels);
    }

    public function getLocation(BaiduMapService $mapService){

        $lat =Input::get('lat',999);
        $lon =Input::get('lon',999);

        if($lat=='undefined'){
            $lat = 999;
        }
        if($lon=='undefined'){
            $lon = 999;
        }

        $location = $mapService->locationByGPS($lon,$lat);
        if(!$location){
            return $this->failure('根据定位获取城市失败。');
        } else {
            //定位
            $data['location'] =$location;
        }

        return $this->success($data);

    }

	/**
     * 获取市级首页数据
	 * @return mixed
	 */
	public function getCityData(AdService $adService,TourService $tour_service,PintuanService $tuanService,
        BaiduMapService $mapService,StoreService $storeService,TourOrderService $toService,
        LayoutRecommendService $layoutService,CacheService $cacheService){

        //参数
        //【经纬度】
        //    lat   经度
        //    lon   维度
        //【查询等级】
        //    level city or country
        $firstrow = Input::get('firstrow',0);
        $pagesize = Input::get('pagesize',10);

        $lat =Input::get('lat',999);
        $lon =Input::get('lon',999);

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
//        $level =Input::get('level','');
        $province = Input::get('province');
        $city = Input::get('city');
        $country =Input::get('district');

        //define
        $data = [
            'share_url'=>config('WAP_URL'),
//            'location'=>[],
            'carousels' => [],
            'tour_cates'=>[],
            'tuans' =>[],
            'villages' =>[],
            'evalutions'=>[],
            'recommends' =>[],
        ];

        if($firstrow==0){
            $saved = $cacheService->getCityData($province.$city.$country);
            if($saved){
                return $this->success($saved);
            }
        }

//        $location = $mapService->locationByGPS($lon,$lat);
//        if(!$location){
//            //return $this->failure('根据定位获取城市失败。');
//            //定位
//            $data['location'] =[];
//        } else {
//            //定位
//            $data['location'] =$location;
//        }

        //轮播图
        $data['carousels'] =$adService->getCityAdByCode($province,$city,$country,'city_home_top_ad');

        //线路主题
        $data['tour_cates'] =$tour_service->getTourCategories();

        //集结令
        $result = $tuanService->getJijielingTuanList($province,$city,$country,0,3);
        if($result['result']==false){
            return $this->failure($result['msg']);
        } else {
            $data['tuans'] = $result['data'];
        }

        //美丽乡村
        $result = $storeService->getRecommendStores($province,$city,$country,0,10);
        if($result['result']==false){
            return $this->failure($result['msg']);
        } else {
            $data['villages'] = $result['data'];
        }

        //乡粉分享
        $result =$toService->getSimpleComments($province,$city,$country,0,3);
        if($result['result']==false){
            return $this->failure($result['msg']);
        } else {
            $data['evalutions'] = $result['data'];
        }

        //精彩推荐
        $result =$layoutService->getLayoutRecommends($province,$city,$country,$firstrow,$pagesize);
        if($result['result']==false){
            return $this->failure($result['msg']);
        } else {
            $data['recommends'] = $result['data'];
        }

        //缓存各省市区的首页数据
        if($firstrow==0){
            $cacheService->setCityData($province.$city.$country,$data);
        }

		return $this->success($data);

	}

    /**
     *
     * @return mixed
     */
    public function search(){

        //参数
        //
        // search_type 搜索类型 all-全部 tour or restaurant or hotel or goods or landowner
        // keyword 关键字
        // sorttype	1 销量 2 人气 3 最新 4 价格  (未使用)
        // sort	asc or desc

        $search_type = Input::get('search_type','tour');
        $keyword = Input::get('keyword','');
        $sorttype = Input::get('sort_type');
        $sorting = Input::get('sort','desc');
        $firstrow = Input::get('firstrow',0);
        $pagesize = Input::get('pagesize',10);
        $lat =Input::get('lat',999);
        $lon =Input::get('lon',999);
		
		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
		
        $time = gmtime();

        $datas = [];

        switch($search_type){
            case 'tour':
                $datas = $this->search_tour($keyword,$sorttype,$lat,$lon,$time,$sorting,$firstrow,$pagesize);
                break;
            case 'restaurant':
                $datas = $this->search_restaurant($keyword,$sorttype,$lat,$lon,$sorting,$firstrow,$pagesize);
                break;
            case 'hotel':
                $datas = $this->search_hotel($keyword,$sorttype,$lat,$lon,$sorting,$firstrow,$pagesize);
                break;
            case 'goods':
                $datas = $this->search_goods($keyword,$sorttype,$sorting,$firstrow,$pagesize);
                break;
            case 'landowner':
                $datas = $this->search_landowner($keyword,$sorttype,$lat,$lon,$sorting,$firstrow,$pagesize);
                break;
            default:
                return $this->failure('未实现');
        }

        return $this->success($datas);

    }

    private function search_tour($keyword,$sorttype,$lat,$lon,$time,$sorting,$firstrow,$pagesize){
        switch ($sorttype){
            case 1:
                $orderby = 'tour_statistics.sales';
                break;
            case 2:
                $orderby = 'tour_statistics.views';
                break;
            case 3:
                $orderby = 'tour.last_update';
                break;
            case 4:
                $orderby = 'tour.price_a';
                break;
            default:
                $orderby = 'tour_statistics.views';
        }

        //获取数据
        $query = DB::table('tour')
            ->join('store', 'tour.store_id', '=', 'store.store_id')
            ->join('tour_statistics','tour.tour_id', '=', 'tour_statistics.tour_id')
            // ->join('tour_schedule','tour.tour_id','=','tour_schedule.tour_id')
            ->where('tour.if_show',1)
            ->where('tour.closed',0)
            ->where('store.state',1)
            // ->where('open_date','>',$time)
            ->where(function ($query2) use($keyword){
                $query2->where('tour.tour_name','like','%'.$keyword.'%')
                       ->orWhere('tour.tags','like','%'.$keyword.'%');
            })
            ->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-tb_tour.latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(tb_tour.latitude*pi()/180)* pow(sin( ($lon*pi()/180-tb_tour.longitude*pi()/180)/2),2)))*1000) as distance,
        tour_sn,tour_name,short_name,default_image,price_a,tb_tour.province,tb_tour.city,tb_tour.country"),'tour.tags','tour.tour_id'/*,'tour_schedule.groupbuy_config'*/)
            ->orderBy($orderby,$sorting)
            ->skip($firstrow)->take($pagesize);

        $tour = $query->get();
            
        // $dd = [];
        // // 处理搜索出旅游路线数据 groupbuy_config代表最低价格
        // foreach ($tour as $key => $value)
        // {
        //     $value->type = 'tour';
        //     $price_min = '';//最低价格
        //     foreach (json_decode($value->groupbuy_config)->prices as $item)
        //     {
        //         if ($price_min > $item->price) {
        //             $tour[$key]->groupbuy_config = $price_min = $item->price;
        //         }else {
        //             $tour[$key]->groupbuy_config = $price_min = $item->price;
        //         }
        //     }

        //     if($dd){
        //         if(array_key_exists($value->tour_id, $dd)){
        //             $price = $dd[$value->tour_id];//取出数组中已存在的价格
        //             if($price - $value->groupbuy_config>0){
        //                $dd[$value->tour_id] = $value->groupbuy_config;
        //                $tour[$key]->groupbuy_config = $value->groupbuy_config;
        //             }
        //             unset($tour[$key]);
        //         }else{
        //             $dd[$value->tour_id] = $value->groupbuy_config;
        //             $tour[$key]->groupbuy_config = $value->groupbuy_config;
        //         }

        //     }else{
        //         $dd[$value->tour_id] = $value->groupbuy_config;
        //     }
        // }
        // $tour = array_values($tour);
        // dd($tour);

        //编辑结果
        foreach ($tour as $item){
            if(!empty($item->default_image))
            {
                $item->default_image = complete_url($item->default_image);
            }
            if (isset($item->tags))
            {
                $item->tags = trim(str_replace('，', ' ', $item->tags));
                $item->tags = trim(str_replace(',', ' ', $item->tags));
            }

            $item->type = 'tour';

            $item->price_min =$item->price_a;
        }

        return $tour;
    }

    private function search_goods($keyword,$sorttype,$sorting,$firstrow,$pagesize){
        switch ($sorttype){
            case 1:
                $orderby = 'goods_statistics.sales';
                break;
            case 2:
                $orderby = 'goods_statistics.views';
                break;
            case 3:
                $orderby = 'goods.last_update';
                break;
            case 4:
                $orderby = 'goods.price';
                break;
            default:
                $orderby = 'goods_statistics.views';
        }

        //获取数据
        $query = DB::table('goods')
            ->join('store', 'goods.store_id', '=', 'store.store_id')
            ->join('goods_statistics','goods.goods_id', '=', 'goods_statistics.goods_id')
            ->where('goods.if_show',1)
            ->where('goods.closed',0)
            ->where('store.state',1)
            ->where(function ($query2) use($keyword){
                $query2->where('goods.goods_name','like','%'.$keyword.'%')
                       ->orWhere('goods.tags','like','%'.$keyword.'%');
            })
            ->select('goods.goods_id','goods.goods_name','goods.default_image','goods.market_price','goods.price','goods.tags')
            ->orderBy($orderby,$sorting)
            ->skip($firstrow)->take($pagesize);

        //nav实现
        //$time = gmtime();

        $goods = $query->get();

        //编辑结果
        foreach ($goods as $item){
            $item->type = 'goods';
            $item->freight = '';
            if(!empty($item->default_image)){
                $item->default_image = complete_url($item->default_image);
            }
            if (!empty($item->tags))
            {
                $item->tags = trim(str_replace(',', ' ', $item->tags));
                $item->tags = trim(str_replace('，', ' ', $item->tags));
            }
        }

        return $goods;
    }

    private function search_restaurant($keyword,$sorttype,$lat,$lon,$sorting,$firstrow,$pagesize){
        switch ($sorttype){
            case 1:
                $orderby = 'restaurants_statistics.sales';
                break;
            case 2:
                $orderby = 'restaurants_statistics.views';
                break;
            case 3:
                $orderby = 'restaurants.last_update';
                break;
            case 4:
                $orderby = 'restaurants.price';
                break;
            default:
                $orderby = 'restaurants_statistics.views';
        }

        //获取数据
        $query = DB::table('restaurants')
            ->join('store', 'restaurants.store_id', '=', 'store.store_id')
            ->join('restaurants_statistics','restaurants.restaurants_id', '=', 'restaurants_statistics.restaurants_id')
            ->where('restaurants.if_show',1)
            ->where('restaurants.closed',0)
            ->where('store.state',1)
            ->where(function ($query2) use($keyword){
                $query2->where('restaurants.restaurants_name','like','%'.$keyword.'%')
                       ->orWhere('restaurants.tags','like','%'.$keyword.'%');
            })
            ->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-tb_restaurants.latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(tb_restaurants.latitude*pi()/180)* pow(sin( ($lon*pi()/180-tb_restaurants.longitude*pi()/180)/2),2)))*1000) as distance,restaurants_name,short_name,default_image,default_image2,tb_restaurants.province,tb_restaurants.city,tb_restaurants.country"),'restaurants.tags','restaurants.restaurants_id','restaurants.market_price')
            ->orderBy($orderby,$sorting)
            ->skip($firstrow)->take($pagesize);

        $restaurants = $query->get();

        //编辑结果
        foreach ($restaurants as $item){
            $item->type = 'restaurant';
            if(!empty($item->default_image)){
                $item->default_image = complete_url($item->default_image);
            }
            if (!empty($item->tags))
            {
                $item->tags = trim(str_replace(',', ' ', $item->tags));
                $item->tags = trim(str_replace('，', ' ', $item->tags));
            }
        }

        return $restaurants;
    }

    private function search_hotel($keyword,$sorttype,$lat,$lon,$sorting,$firstrow,$pagesize){
        switch ($sorttype){
            case 1:
                $orderby = 'hotels_statistics.sales';
                break;
            case 2:
                $orderby = 'hotels_statistics.views';
                break;
            case 3:
                $orderby = 'hotels.last_update';
                break;
            case 4:
                $orderby = 'hotels.price';
                break;
            default:
                $orderby = 'hotels_statistics.views';
        }

        //获取数据
        $query = DB::table('hotels')
            ->join('store', 'hotels.store_id', '=', 'store.store_id')
            ->join('hotels_statistics','hotels.hotels_id', '=', 'hotels_statistics.hotels_id')
            ->where('hotels.if_show',1)
            ->where('hotels.closed',0)
            ->where('store.state',1)
            ->where(function ($query2) use($keyword){
                $query2->where('hotels.hotels_name','like','%'.$keyword.'%')
                       ->orWhere('hotels.tags','like','%'.$keyword.'%');
            })
            ->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-tb_hotels.latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(tb_hotels.latitude*pi()/180)* pow(sin( ($lon*pi()/180-tb_hotels.longitude*pi()/180)/2),2)))*1000) as distance,hotels_name,short_name,default_image,tb_hotels.province,tb_hotels.city,tb_hotels.country"),'hotels.tags','hotels.hotels_id','hotels.market_price')
            ->orderBy($orderby,$sorting)
            ->skip($firstrow)->take($pagesize);

        $hotels = $query->get();

        //编辑结果
        foreach ($hotels as $item){
            $item->type = 'hotel';
            if(!empty($item->default_image)){
                $item->default_image = complete_url($item->default_image);
            }
            if (!empty($item->tags))
            {
                $item->tags = trim(str_replace(',', ' ', $item->tags));
                $item->tags = trim(str_replace('，', ' ', $item->tags));
            }
        }

        return $hotels;
    }

    private function search_landowner($keyword,$sorttype,$lat,$lon,$sorting,$firstrow,$pagesize){
        switch ($sorttype){
            case 1:
                $orderby = 'landowners_statistics.sales';
                break;
            case 2:
                $orderby = 'landowners_statistics.views';
                break;
            case 3:
                $orderby = 'landowners.last_update';
                break;
            case 4:
                $orderby = 'landowners.price';
                break;
            default:
                $orderby = 'landowners_statistics.views';
        }

        //获取数据
        $query = DB::table('landowners')
            ->join('store', 'landowners.store_id', '=', 'store.store_id')
            ->join('landowners_statistics','landowners.landowners_id', '=', 'landowners_statistics.landowners_id')
            ->where('landowners.if_show',1)
            ->where('landowners.closed',0)
            ->where('store.state',1)
            ->where(function ($query2) use($keyword){
                $query2->where('landowners.landowners_name','like','%'.$keyword.'%')
                       ->orWhere('landowners.tags','like','%'.$keyword.'%');
            })
            ->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-tb_landowners.latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(tb_landowners.latitude*pi()/180)* pow(sin( ($lon*pi()/180-tb_landowners.longitude*pi()/180)/2),2)))*1000) as distance,landowners_name,short_name,default_image,tb_landowners.province,tb_landowners.city,tb_landowners.country"),'landowners.tags','landowners.landowners_id','landowners.price')
            ->orderBy($orderby,$sorting)
            ->skip($firstrow)->take($pagesize);

        $landowners = $query->get();

        //编辑结果
        foreach ($landowners as $item){
            $item->type = 'landowner';
            if(!empty($item->default_image)){
                $item->default_image = complete_url($item->default_image);
            }
            if (!empty($item->tags))
            {
                $item->tags = trim(str_replace(',', ' ', $item->tags));
                $item->tags = trim(str_replace('，', ' ', $item->tags));
            }
        }

        return $landowners;
    }
}
